<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="vue.js"></script>
  <script src="vue-router.js"></script>
  <style>
    .router-link-active {
      background: red;
    }
  </style>
</head>

<body>
  <div id="app">
    <router-link to="/home">首页</router-link>
    <router-link to="/news">新闻页</router-link>
    <router-view></router-view>
  </div>
  <script>
    let Home = {
      template: `
        <div>
          我是首页
         
        </div>
      `
    };
    let News = {
      template: `
        <div>
          我是新闻页
          <button @click="logout">退出登录</button>
        </div>
      `,
      methods:{
        logout(){
          localStorage.removeItem("token");
          this.$router.go(0);
        }
      }
    };
    let Login = {
      template: `
        <div>
          登录页
          <button @click="login">登录</button>  
        </div>
      `,
      methods: {
        login() {
          localStorage.setItem("token", "1234tjgt");
          this.$router.push("/home");
        }
      }
    };
    // 定义一个路由规则
    let routes = [{
        name: "home",
        path: "/home",
        component: Home
      },
      {
        name: "news",
        path: "/news",
        component: News,
        beforeEnter(to,from,next){
          let token = localStorage.getItem("token");
          if(token){
            next();
          }else{
            next("/login")
          }
        }
      },
      {
        name: "login",
        path: "/login",
        component: Login,

      }
    ];
    // 初始化 router对象
    const router = new VueRouter({
      routes
    });
   
    let vm = new Vue({
      el: "#app",
      router
    })
  </script>
</body>

</html>